//******************************************************************************
//  RCR Test Sandbox
//
//	Added open/close simulation. Motor will 'close' until 
//	P1.4 goes high at which point it 'opens' for MAXSTEPS 
//	steps. When MAXSTEPS is reached, motor 'closes' again 
//	and cycle repeats.
//
//           MSP430G2231
//         ---------------   _
//     /|\|           P1.0|-  |
//      | |           P1.1|-  | to stepper
//      --|RST        P1.2|-  |
//        |           P1.3|-  |
//        |               |  -
//        |           P1.4|- pulled down with switch to Vcc
//
//  Jacob Ward
//	Sept. 2011
//  Built with CCS Version 4.2.0
//******************************************************************************

#include <msp430g2231.h>

#define PERIOD (5000)
#define CLOSE (0)
#define OPEN (1)
#define MAXSTEPS (400) // ???

int direction = CLOSE;
int steps = 0;
void main(void)
{
  WDTCTL = WDTPW + WDTHOLD;                 // Stop WDT
  P1DIR |= 0xEF;                            // P1.4 input
  
  P1OUT = 1;
  
  
 	P1IES = 0x00;															// Port 1 interrups triggers on low to high transition
 	P1IE = 0x10;															// P1.4 interrupt enable
 	P1IFG = 0x00;															// clear port 1 interrupt flags
  
  CCTL0 = CCIE;                             // CCR0 interrupt enabled
  CCR0 = PERIOD;
  TACTL = TASSEL_2 + MC_2;                  // SMCLK, contmode
  
  
  _BIS_SR(LPM0_bits + GIE);                 // Enter LPM0 w/ interrupt
}

// Timer A0 interrupt service routine
#pragma vector=TIMERA0_VECTOR
__interrupt void Timer_A (void)
{
	if(direction == OPEN)
	{
		if(steps == MAXSTEPS)
		{
			steps = 0;
			direction = CLOSE;
			return;
		}
	  P1OUT <<= 1;
	  if(P1OUT > 8)
	  	P1OUT = 1;
		steps++;
	}
	else // Closing
	{
		/*
		if(steps == MAXSTEPS)
		{
			steps = 0;
			direction = OPEN;
			return;
		}
		*/
		P1OUT >>= 1;
		if(P1OUT == 0)
			P1OUT = 8;
	}
  CCR0 += PERIOD;                            // Add Offset to CCR0
}

#pragma vector = PORT1_VECTOR
__interrupt void Port1(void)
{
	P1IFG = 0x00;
	direction = OPEN;
}
